import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqGetUserInfo,
  reqLogout
} from '@/api'
import { setToken, getToken, removeToken } from '@/utills/token'

const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}

const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  CLEAR(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}

const actions = {
  /**
   * 获取验证码
   * @param {*} param0
   * @param {*} phone：手机号
   * @returns
   */
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code === 200) {
      commit('GETCODE', result.data)
      return 'OK'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  /**
   * 用户注册
   * @param {*} param0
   * @param {*} user：用户注册信息
   */
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    if (result.code === 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error(result.message))
    }
  },
  /**
   * 用户登录
   * @param {*} param0
   * @param {*} user：用户信息
   */
  async userLogin({ commit }, user) {
    let result = await reqUserLogin(user)
    if (result.code === 200) {
      commit('USERLOGIN', result.data.token)
      setToken(result.data.token)
      return 'OK'
    } else {
      return Promise.reject(new Error(result.message))
    }
  },
  /**
   * 获取用户信息
   */
  async getUserInfo({ commit }) {
    let result = await reqGetUserInfo()
    console.log(result)
    if (result.code === 200) {
      commit('GETUSERINFO', result.data)
      return 'OK'
    } else {
      return Promise.reject(new Error(result.message))
    }
  },
  /**
   * 退出登录
   * @param {*} param0
   */
  async userLogout({ commit }) {
    let result = await reqLogout()
    if (result.code === 200) {
      commit('CLEAR')
      return 'OK'
    } else {
      return Promise.reject(new Error('fail'))
    }
  }
}

const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}
